//
//  LJNewfeatureView.swift
//  LJWeibo
//
//  Created by 连俊杨 on 2017/10/24.
//  Copyright © 2017年 yang_ljun. All rights reserved.
//

import UIKit

class LJNewfeatureView: UIView {
    
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var enterButton: UIButton!
    @IBOutlet weak var pageControl: UIPageControl!
    
    @IBAction func enterWeibo() {
        removeFromSuperview()
    }
    
    /// 类初始化方法，从xib加载本类
    class func newFeatureView() -> LJNewfeatureView {
        let nib = UINib(nibName: "LJNewfeatureView", bundle: nil)
        let view = nib.instantiate(withOwner: nil, options: nil)[0] as? LJNewfeatureView
        
        view?.frame = UIScreen.main.bounds
        
        return view!
    }
    
    override func awakeFromNib() {
        let count = 4
        let rect = UIScreen.main.bounds
        
        for i in 0..<count {
            let imageName = "new_feature_\(i+1)"
            let image = UIImage(named: imageName)
            let iv = UIImageView(image: image)
            
            iv.frame = rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0)
            
            scrollView.addSubview(iv)
        }
        
        /// scrollView的属性设置
        scrollView.contentSize = CGSize(width: CGFloat(count + 1) * rect.width, height: rect.height)
        scrollView.bounces = false
        scrollView.isPagingEnabled = true
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.delegate = self
        
        enterButton.isHidden = true
    }
}

extension LJNewfeatureView: UIScrollViewDelegate {
    // scrolleView 滑动减速
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        /// 如果==4，就移除父视图
        if page == scrollView.subviews.count {
            removeFromSuperview()
        }
        
        enterButton.isHidden = !(page == scrollView.subviews.count - 1)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        enterButton.isHidden = true
        
        let index = Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5)
        pageControl.currentPage = index
        
        pageControl.isHidden = (index == scrollView.subviews.count)
    }
}
